﻿using Aker.DevTeam;
using Aker.Hammadde;
using Aker.MainForms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Aker.Cikislar
{
    public partial class Cikislar : XForm
    {
        int Tip; //1:Çıkışlar 2:Çıkış Emirleri 3:Çıkış Takip
        public Cikislar(int tip)
        {
            InitializeComponent();
            this.Tip = tip;
        }

        private void Cikislar_Load(object sender, EventArgs e)
        {
            Bind();

            GridMenu gm = GridManager.GetManager(gv).GridMenu;
            if (Tip == 1)
            {
                this.Text = "Çıkışlar";

                gm.AddMenu("İrsaliye Yazdır", Irsaliye);
                if (AppSession.UserInfo.Yonetici || AppSession.UserInfo.UserId == 20 || AppSession.UserInfo.UserId == 24)
                    gm.AddMenu("Çıkış Birleştir", CikisBirlestir);
                splitterBottom.PanelVisibility = SplitPanelVisibility.Panel1;
            }
            else if (Tip == 2)
            {
                this.Text = "Satılan İplik Çıkışları";

                GridMenu gmDetail = GridManager.GetManager(gvDetail).GridMenu;
                gmDetail.AddMenu("Çıkış Yap", CikisYap);

                gm.AddMenu("Çıkış Emri Yazdır", CikisEmri);
                gm.AddMenu("İrsaliye Yazdır", Irsaliye);
                if (AppSession.UserInfo.Yonetici || AppSession.UserInfo.UserId == 20)
                    gm.AddMenu("Çıkış Birleştir", CikisBirlestir);
                gm.AddMenu("Çeki Listesi Yazdır", Ceki);
                splitterBottom.PanelVisibility = SplitPanelVisibility.Both;

                gv.MakeColumnInvisible("CikisYontemi", "CikisTipi");

                gv.ViewCaption = "Çıkışlar";
                gv.OptionsView.ShowViewCaption = true;
                gvDetail.ViewCaption = "Çıkış Emirleri";
                gvDetail.OptionsView.ShowViewCaption = true;
                gvDetailSub.ViewCaption = "Gerçekleşen Çıkışlar";
                gvDetailSub.OptionsView.ShowViewCaption = true;
            }
            else if (Tip == 3)
            {
                this.Text = "Çıkış Takip";
                splitter.PanelVisibility = SplitPanelVisibility.Panel1;
                splitterBottom.PanelVisibility = SplitPanelVisibility.Panel1;
            }

            gv.MakeColumnInvisible("CikisYontemiId", "CikisTipiId");
            gvDetail.MakeColumnInvisible("CikisId", "CikisLinesId");
            gvDetail.AddSummary("CikilanMetre", "CikilanAdet", "CikilanKG");

            gvDetailSub.MakeColumnInvisible("CikisId", "Grup");

            gv.MakeReadOnly();
            gvDetailSub.MakeReadOnly();

            gv.SetCaptions("CikisId:Çıkış No", "POrderId:Sip.No", "OlusturulmaTarihi:Oluşturma", "CikilacakTarih:Çıkılacak Tarih",
                                                "CikisAciklama:Açıklama", "Cikan:Oluşturan", "CikilanYer:Çıkılan Yer", "IrsaliyeNo:İrsaliye No", "CikisTipi:Çıkış Tipi", "CikisYontemi:Çıkış Yöntemi"
                                                );


            gvDetail.SetCaptions("RollId:Top No", "IrsaliyeAciklama:İrsaliye Açıklama", "CikisEmrindekiKG:Talep Edilen KG",
                                    "CikisEmriLinesId:Çıkış Emri No", "Grup:İplik Grup", "Adet:Talep Edilen Adet", "CikilanAdet:Çıkılan Adet", "CikilanKG:Çıkılan KG",
                                    "CikilanMetre:Çıkılan MT", "Article:Artikel", "Design:Desen", "Weight:Ağırlık", "Composition:Karışım"
                                    );

            if (gvDetail.Columns["IrsaliyeAciklama"] != null)
                gvDetail.Columns["IrsaliyeAciklama"].VisibleIndex = 0;

            if (gvDetail.Columns["Kartela"] != null)
                gvDetail.Columns["Kartela"].VisibleIndex = 1;

            gvDetailSub.SetCaptions("CikisLinesId:Çıkış Satırı No", "HammaddeId:İplik No", "CikilanKG:Çıkılan KG", "Hammadde:İplik");
            gvDetailSub.AddSummary("CikilanKG");
            gv.BestFitColumns();
            gvDetail.BestFitColumns();
            gvDetailSub.BestFitColumns();
            gv.FocusedRowChanged += gv_FocusedRowChanged;
            gv.EnableComplexFiltering("CikilanYer", "CikisAciklama");

            gv.RowStyle += gv_RowStyle;
            gv.SelectionChanged += gv_SelectionChanged;
            //gv.RowCellClick += gv_RowCellClick;


            
            gv.OptionsSelection.EnableAppearanceFocusedCell = true;
            gv.OptionsSelection.EnableAppearanceFocusedRow = true;
            
            gv.Appearance.FocusedRow.BackColor = Color.FromArgb(255, 255, 192);
            gv.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect;
            
            gv.Appearance.SelectedRow.BackColor = Color.FromArgb(255, 255, 192);
            gv.Appearance.SelectedRow.Options.UseBackColor = true;
        }

        void gv_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
           // gv.RefreshRow(e.ControllerRow);
        }

        void gv_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            //int[] selecteds = gv.GetSelectedRows();
            //if (selecteds.Contains(e.RowHandle))
            //    e.Appearance.BackColor = e.Appearance.BackColor = Color.YellowGreen;
            //else
            //    e.Appearance.BackColor = Color.White;
        }

        private void CikisBirlestir(object sender, EventArgs e)
        {
            int[] rhs = gv.GetSelectedRows();

            if (rhs.Length > 1)
            {
                List<int> ids = new List<int>();
                foreach (int id in rhs)
                    ids.Add(gv.GetDataRow(id)["CikisId"].ToIntNN());

                int master = ids[0];
                ids.RemoveAt(0);
                string childs = String.Join(",", ids);

                ShowInfo(string.Format("Korunacak Çıkış No:{0}, Taşınacak Çıkış No(lar):{1}", master, childs));

                Data.DM.ExecuteNonQuery("CikisBirlestir", master, childs);

            }

        }

        //void gv_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        //{
        //    if (e.RowHandle > -1)
        //    {
        //        if (e.Column.FieldName == "Seç")
        //        {
        //            DataRow drCurrent = gv.GetDataRow(e.RowHandle);
        //            bool selected = (bool)drCurrent["Seç"];
        //            if (selected)
        //                gv.SetRowCellValue(e.RowHandle, "Seç", false);
        //            else
        //                gv.SetRowCellValue(e.RowHandle, "Seç", true);
        //        }
        //    }
        //}

        private void Bind()
        {
            this.Cursor = Cursors.WaitCursor;
            int focusedRH = gv.FocusedRowHandle;

            DataSet ds = Data.DM.ExecuteDataSet("GetCikislar", Tip);

            if (Tip == 1)
            {

                if (chkIrsaliye.Checked)
                {
                    DataRow[] drs = (ds.Tables[0].Select("isnull(IrsaliyeNo,'') <> ''"));
                    foreach (DataRow dr in drs)
                        ds.Tables[0].Rows.Remove(dr);
                }

                DataTable dtDetail = ds.Tables[1];
                ds.Relations.Add("FK", ds.Tables[0].Columns["CikisId"], ds.Tables[1].Columns["CikisId"]);

                BindingSource bs = new BindingSource(ds, ds.Tables[0].TableName);
                BindingSource bsDetail = new BindingSource(bs, "FK");

                gv.Init(bs);
                gvDetail.Init(bsDetail);
            }
            else if (Tip == 2)
            {
                DataTable dtMaster = ds.Tables[0];
                DataTable dtDetail = ds.Tables[1];
                DataTable dtDetailSub = ds.Tables[2];

                ds.Relations.Add("FK", dtMaster.Columns["CikisId"], dtDetail.Columns["CikisId"]);
                ds.Relations.Add("FKSub", dtDetail.Columns["CikisId"], dtDetailSub.Columns["CikisId"]);

                ds.Relations.Add("FKSum", new DataColumn[] { dtDetail.Columns["CikisId"], dtDetail.Columns["Grup"] }, new DataColumn[] { dtDetailSub.Columns["CikisId"], dtDetailSub.Columns["Grup"] });

                dtDetail.Columns.Add("CikilanKG", typeof(decimal), "SUM(Child(FKSum).CikilanKG)");
                dtDetail.Columns.Add("CikilanAdet", typeof(int), "COUNT(Child(FKSum).CikilanKG)");

                BindingSource bs = new BindingSource(ds, dtMaster.TableName);
                BindingSource bsDetail = new BindingSource(bs, "FK");
                BindingSource bsDetailSub = new BindingSource(bsDetail, "FKSub");

                gv.Init(bs);
                gvDetail.Init(bsDetail);
                gvDetailSub.Init(bsDetailSub);

                gv.MakeColumnInvisible("CikisYontemi", "CikisTipi");

                gv.ViewCaption = "Çıkışlar";
                gv.OptionsView.ShowViewCaption = true;
                gvDetail.ViewCaption = "Çıkış Emirleri";
                gvDetail.OptionsView.ShowViewCaption = true;
                gvDetailSub.ViewCaption = "Gerçekleşen Çıkışlar";
                gvDetailSub.OptionsView.ShowViewCaption = true;


            }
            else if (Tip == 3)
            {
                this.Text = "Çıkış Takip";

                gv.Init(ds.Tables[0]);
                splitter.PanelVisibility = SplitPanelVisibility.Panel1;
                splitterBottom.PanelVisibility = SplitPanelVisibility.Panel1;
            }

            gvDetail.FormatAsNumber("CikilanKG");


            gv.MakeColumnInvisible("CikisYontemiId", "CikisTipiId");
            gvDetail.MakeColumnInvisible("CikisId", "CikisLinesId");
            gvDetail.AddSummary("CikilanMetre", "CikilanAdet", "CikilanKG");

            gvDetailSub.MakeColumnInvisible("CikisId", "Grup");

            gv.MakeReadOnly();
            gvDetailSub.MakeReadOnly();

            gv.SetCaptions("CikisId:Çıkış No", "POrderId:Sip.No", "OlusturulmaTarihi:Oluşturma", "CikilacakTarih:Çıkılacak Tarih",
                                                "CikisAciklama:Açıklama", "Cikan:Oluşturan", "CikilanYer:Çıkılan Yer", "IrsaliyeNo:İrsaliye No", "CikisTipi:Çıkış Tipi", "CikisYontemi:Çıkış Yöntemi"
                                                );


            gvDetail.SetCaptions("RollId:Top No", "IrsaliyeAciklama:İrsaliye Açıklama", "CikisEmrindekiKG:Talep Edilen KG",
                                    "CikisEmriLinesId:Çıkış Emri No", "Grup:İplik Grup", "Adet:Talep Edilen Adet", "CikilanAdet:Çıkılan Adet", "CikilanKG:Çıkılan KG",
                                    "CikilanMetre:Çıkılan MT", "Article:Artikel", "Design:Desen", "Weight:Ağırlık", "Composition:Karışım"
                                    );

            if (gvDetail.Columns["IrsaliyeAciklama"] != null)
                gvDetail.Columns["IrsaliyeAciklama"].VisibleIndex = 0;

            gvDetailSub.SetCaptions("CikisLinesId:Çıkış Satırı No", "HammaddeId:İplik No", "CikilanKG:Çıkılan KG", "Hammadde:İplik");
            gvDetailSub.AddSummary("CikilanKG");
            gv.BestFitColumns();
            gvDetail.BestFitColumns();
            gvDetailSub.BestFitColumns();



            gv.BestFitColumns();
            if (focusedRH > -1)
                gv.FocusedRowHandle = focusedRH;

            FormatDetail();
            this.Cursor = Cursors.Default;
        }

        private void CikisYap(object sender, EventArgs e)
        {
            DataRow dr = gv.GetFocusedDataRow();
            int CikisId = dr["CikisId"].ToIntNN();

            int[] selected = gvDetail.GetSelectedRows();
            List<string> filters = new List<string>();
            foreach (int i in selected)
                filters.Add(gvDetail.GetRowCellValue(i, "CikisEmriLinesId").ToString());

            HammaddeCikis hc = new HammaddeCikis(CikisId, string.Join(",", filters));
            hc.WindowState = FormWindowState.Maximized;
            if (hc.ShowDialog() == DialogResult.OK)
                Bind();
        }

        private void CikisEmri(object sender, EventArgs e)
        {
            if (gv.FocusedRowHandle > -1)
            {
                DataRow dr = gv.GetFocusedDataRow();
                int CikisId = dr["CikisId"].ToIntNN();

                CikisEmriReport ce = new CikisEmriReport(CikisId);

                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), ce, "", "Çıkış No:" + CikisId);
            }
        }

        private void Irsaliye(object sender, EventArgs e)
        {
            if (gv.FocusedRowHandle > -1)
            {
                DataRow dr = gv.GetFocusedDataRow();
                int cikisId = dr["CikisId"].ToIntNN();
                string iNo = dr["IrsaliyeNo"].ToStringNN();
                if (iNo == "" || AppSession.UserInfo.UserId == 2 || AppSession.UserInfo.UserId == 5)
                {
                    YeniIrsaliye sNo = new YeniIrsaliye(cikisId);
                    if (sNo.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                        return;

                    gv.SetFocusedRowCellValue("IrsaliyeNo", sNo.IrsaliyeNo.Substring(2));
                }

                Aker.Cikislar.IrsaliyeReport ir = new IrsaliyeReport(cikisId);
                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), ir, "", "Çıkış No:" + cikisId);
            }
        }

        private void Ceki(object sender, EventArgs e)
        {
            if (gv.FocusedRowHandle > -1)
            {
                DataRow dr = gv.GetFocusedDataRow();
                int cikisId = dr["CikisId"].ToIntNN();
                Aker.Cikislar.CekiReport cr = new CekiReport(cikisId);

                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), cr, "", "Çıkış No:" + cikisId);
            }
        }

        private void gv_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FormatDetail();
        }

        private void FormatDetail()
        {
            DataRow dr = gv.GetFocusedDataRow();
            if (dr == null)
                return;

            int yontem = dr["CikisYontemiId"].ToIntNN();
            string iNo = dr["IrsaliyeNo"].ToStringNN();

            if (iNo == "")
                gvDetail.MakeReadOnly("IrsaliyeAciklama");
            else
                gvDetail.MakeReadOnly();

            if (yontem == 1) //top
            {
                string[] cols = new string[] { "IrsaliyeAciklama", "Thumbnail", "ProductId", "RollId", "Article", "PartiNo", "Design", "Weight", "Composition", "CikilanMetre", "CikilanKG", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                gvDetail.SetVisibleIndex(cols);
            }
            else if (yontem == 2 || yontem == 10) //hammadde - Terminal Doğrudan çıkış
            {
                string[] cols = new string[] { "IrsaliyeAciklama", "HammaddeId", "Hammadde", "CikilanKG", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                gvDetail.SetVisibleIndex(cols);
            }
            else if (yontem == 3) //üretim
            {
                string[] cols = new string[] { "IrsaliyeAciklama", "ProductId", "Article", "PartiNo", "Design", "Weight", "Composition", "CikilanMetre", "CikilanKG", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                gvDetail.SetVisibleIndex(cols);
            }
            else if (yontem == 4) //sepet
            {
                string[] cols = new string[] { "IrsaliyeAciklama", "Thumbnail", "ProductId", "RollId", "Article","Kartela", "PartiNo", "Design", "Weight", "Composition", "HammaddeId", "Hammadde", "CikilanKG", "CikilanMetre", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                gvDetail.SetVisibleIndex(cols);
            }
            else if (yontem == 5) //İplik Satış
            {
                string[] cols = null;
                if (Tip == 1) //Çıkışlar
                    cols = new string[] { "IrsaliyeAciklama", "HammaddeId", "Hammadde", "CikilanKG", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                else if (Tip == 2 || Tip == 3) //Çıkış Emirleri - Çıkış Takip
                    cols = new string[] { "Grup", "BirimAdet", "CikisEmrindekiKG", "Adet", "CikilanKG", "CikilanAdet", "Fiyat", "Parabirimi", "OdemeSekli", "Vade", "OdemeNotu" };
                //else if (Tip == 3) //Çıkış Emirler
                //    cols = new string[] { "Grup", "BirimAdet", "CikisEmrindekiKG", "Adet", "CikilanKG", "CikilanAdet" };

                gvDetail.SetVisibleIndex(cols);
            }

            gvDetail.BestFitColumns();
            gvDetailSub.BestFitColumns();
        }

        private void gvDetail_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            int cikisLinesId = gvDetail.GetRowCellValue(e.RowHandle, "CikisLinesId").ToIntNN();
            string val = e.Value.ToStringNN();
            Data.DM.ExecuteNonQuery("UpdIrsaliyeAciklama", cikisLinesId, val);
            DataTable d = gvDetail.GetDataRow(e.RowHandle).Table;
        }

        private void btnGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Bind();
        }

        private void chkIrsaliye_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Bind();
        }
    }
}